// src/utils/config.ts
import fs from 'fs-extra';
import path from 'path';
import { logger } from './logger';

export interface ProjectConfig {
  projectName: string;
  type: 'main' | 'sub';
  framework?: 'react' | 'vue' | 'vanilla';
  port?: number;
  features: string[];
}

// 读取配置文件
export const readConfig = async (projectPath: string): Promise<ProjectConfig | null> => {
  const configPath = path.join(projectPath, '.microfrontend.config.json');
  
  if (await fs.pathExists(configPath)) {
    try {
      return await fs.readJson(configPath);
    } catch (error) {
      logger.warning('读取配置文件失败:', error);
      return null;
    }
  }
  
  return null;
};

// 写入配置文件
export const writeConfig = async (projectPath: string, config: ProjectConfig): Promise<void> => {
  const configPath = path.join(projectPath, '.microfrontend.config.json');
  
  try {
    await fs.writeJson(configPath, config, { spaces: 2 });
    logger.success('配置文件已生成');
  } catch (error) {
    logger.error('写入配置文件失败:', error);
    throw error;
  }
};

// 验证项目名称
export const validateProjectName = (name: string): boolean => {
  if (!name) {
    logger.error('项目名称不能为空');
    return false;
  }
  
  if (!/^[a-z0-9-]+$/.test(name)) {
    logger.error('项目名称只能包含小写字母、数字和连字符');
    return false;
  }
  
  return true;
};